<template>
  <div class="page-container dashboard">
    <div class="page-content">
      <!-- 欢迎信息 -->
      <div class="welcome-banner">
        <h1>🚀 欢迎, {{ system.info.hostname || 'Mobox User' }}!</h1>
        <p>您的专业单板机管理平台已准备就绪。</p>
      </div>

      <!-- 关键指标概览 -->
      <el-row :gutter="20" class="status-cards">
        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="card-content">
              <h3><el-icon><Odometer /></el-icon> CPU</h3>
              <p class="status-value">{{ system.status.cpu_percent?.toFixed(1) || 0 }}%</p>
              <el-progress :percentage="system.status.cpu_percent || 0" :show-text="false" :color="cpuColor" />
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="card-content">
              <h3><el-icon><DataLine /></el-icon> 内存</h3>
              <p class="status-value">{{ system.status.memory_percent?.toFixed(1) || 0 }}%</p>
              <el-progress :percentage="system.status.memory_percent || 0" :show-text="false" color="#E6A23C" />
            </div>
          </el-card>
        </el-col>
        
        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="card-content">
              <h3><el-icon><Folder /></el-icon> 磁盘</h3>
              <p class="status-value">{{ system.status.disk_percent?.toFixed(1) || 0 }}%</p>
              <el-progress :percentage="system.status.disk_percent || 0" :show-text="false" color="#909399" />
            </div>
          </el-card>
        </el-col>

        <el-col :span="6">
          <el-card class="status-card" shadow="hover">
            <div class="card-content">
              <h3><el-icon><Sunny /></el-icon> 温度</h3>
              <p class="status-value">{{ system.status.temperature?.toFixed(1) || 'N/A' }}°C</p>
               <div class="status-subtext">系统核心温度</div>
            </div>
          </el-card>
        </el-col>
      </el-row>

      <!-- 快捷操作 -->
      <div class="quick-actions">
        <h2>⚡ 快捷操作</h2>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-button type="primary" size="large" @click="$router.push('/monitor')" class="action-btn" plain>
              <el-icon><PieChart /></el-icon> 完整系统监控
            </el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="success" size="large" @click="$router.push('/network')" class="action-btn" plain>
              <el-icon><Link /></el-icon> 配置网络连接
            </el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="warning" size="large" @click="$router.push('/docker')" class="action-btn" plain>
              <el-icon><Box /></el-icon> 管理Docker容器
            </el-button>
          </el-col>
          <el-col :span="6">
            <el-button type="info" size="large" @click="triggerUpdateCheck" class="action-btn" plain>
              <el-icon><Refresh /></el-icon> 检查镜像更新
            </el-button>
          </el-col>
        </el-row>
      </div>

      <!-- 设备与网络信息 -->
       <el-row :gutter="20">
        <el-col :span="12">
            <el-card class="info-card" shadow="hover">
                <template #header><h3><el-icon><InfoFilled /></el-icon> 设备信息</h3></template>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="设备ID">{{ system.info.box_id }}</el-descriptions-item>
                    <el-descriptions-item label="设备型号">{{ system.info.machine }}</el-descriptions-item>
                    <el-descriptions-item label="系统版本">{{ system.info.os }}</el-descriptions-item>
                    <el-descriptions-item label="运行时间">{{ formatUptime(system.status.uptime) }}</el-descriptions-item>
                </el-descriptions>
            </el-card>
        </el-col>
         <el-col :span="12">
            <el-card class="info-card" shadow="hover">
                <template #header><h3><el-icon><Connection /></el-icon> 网络信息</h3></template>
                <el-descriptions :column="1" border>
                    <el-descriptions-item label="IP 地址">{{ network.settings?.ip || 'N/A' }}</el-descriptions-item>
                    <el-descriptions-item label="子网掩码">{{ network.settings?.subnet || 'N/A' }}</el-descriptions-item>
                    <el-descriptions-item label="网关地址">{{ network.settings?.gateway || 'N/A' }}</el-descriptions-item>
                    <el-descriptions-item label="DNS服务器">{{ network.settings?.dns || 'N/A' }}</el-descriptions-item>
                </el-descriptions>
            </el-card>
        </el-col>
       </el-row>
    </div>
    
    <!-- 镜像更新进度弹窗 -->
    <el-dialog 
      v-model="updateDialog.visible" 
      title="Docker镜像更新" 
      width="600px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      center
    >
      <ImageUpdateStatus />
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, onMounted, onUnmounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import api from '@/services/api';
import { formatUptime } from '@/utils/formatters';
import ImageUpdateStatus from '@/components/ImageUpdateStatus.vue';
import { io } from 'socket.io-client';

const system = reactive({
  info: {},
  status: {},
});

const network = reactive({
    settings: {}
});

const updateDialog = reactive({
  visible: false
});

let intervalId = null;
let socket = null;

// 根据CPU使用率返回不同颜色
const cpuColor = computed(() => {
    const usage = system.status.cpu_percent || 0;
    if (usage > 80) return '#F56C6C';
    if (usage > 60) return '#E6A23C';
    return '#67C23A';
});

// 触发更新检查
const triggerUpdateCheck = async () => {
  try {
    updateDialog.visible = true;
    const response = await api.post('/api/image-updates/check', {
      force: true,
      school_name: '测试学校'
    });
    
    if (response.data.code === 0) {
      ElMessage.success('更新检查已开始');
    } else {
      ElMessage.error('启动更新检查失败');
    }
  } catch (error) {
    console.error('触发更新检查失败:', error);
    ElMessage.error('无法启动更新检查');
  }
};

// 初始化WebSocket连接监听更新事件
const initUpdateSocket = () => {
  socket = io('/updates', {
    transports: ['websocket', 'polling']
  });
  
  // 监听更新检查完成事件
  socket.on('check_complete', (data) => {
    if (data.available_updates && data.available_updates.length > 0) {
      // 自动弹出更新窗口
      updateDialog.visible = true;
      ElMessage.warning(`发现 ${data.available_updates.length} 个镜像更新`);
    } else if (!data.error) {
      ElMessage.success('所有镜像都是最新版本');
    }
  });
  
  // 监听更新完成事件
  socket.on('update_complete', (data) => {
    if (data.success) {
      ElMessage.success('镜像更新完成！');
      setTimeout(() => {
        updateDialog.visible = false;
      }, 3000);
    } else {
      ElMessage.error('镜像更新失败');
    }
  });
  
  // 监听错误事件
  socket.on('error', (error) => {
    console.error('Socket连接错误:', error);
  });
};

const fetchData = async () => {
  // 使用独立的try/catch来分别获取数据，避免一个失败导致全部失败
  try {
    const [infoRes, statusRes] = await Promise.all([
      api.getSystemInfo(),
      api.getSystemStatus(),
    ]);
    system.info = infoRes.data.data;
    system.status = statusRes.data;
  } catch (err) {
    ElMessage.error('获取核心系统数据失败！');
    console.error('获取系统信息/状态失败:', err);
  }

  try {
    const networkRes = await api.getNetworkSettings();
    network.settings = networkRes.data.data;
  } catch (err) {
    // 网络数据获取失败是次要的，只在控制台提示
    console.warn('获取网络数据失败:', err);
    // 可以设置一个默认值或保持上一次的状态
    network.settings = network.settings || {};
  }
};

onMounted(() => {
  fetchData();
  intervalId = setInterval(fetchData, 5000); // 5秒刷新一次
  
  // 初始化更新监听
  initUpdateSocket();
});

onUnmounted(() => {
  if (intervalId) {
    clearInterval(intervalId);
  }
  
  // 断开Socket连接
  if (socket) {
    socket.disconnect();
  }
});
</script>

<style scoped>
.dashboard {
  animation: fadeIn 0.5s ease-in-out;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.welcome-banner {
  background: linear-gradient(135deg, #7367F0, #A582F7);
  color: white;
  padding: 30px;
  border-radius: 12px;
  margin-bottom: 20px;
  box-shadow: 0 8px 25px -8px #7367f0;
}

.welcome-banner h1 {
  margin: 0 0 10px 0;
  font-size: 28px;
}

.status-cards .status-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.status-cards .status-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0,0,0,0.1);
}

.card-content {
  text-align: left;
}

.card-content h3 {
  margin: 0 0 15px 0;
  color: #606266;
  font-size: 16px;
  font-weight: 600;
  display: flex;
  align-items: center;
}
.card-content h3 .el-icon {
    margin-right: 8px;
    font-size: 18px;
}

.status-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin: 0 0 10px 0;
}
.status-subtext {
    font-size: 12px;
    color: #909399;
}

.quick-actions, .info-card {
  margin-top: 20px;
}

.quick-actions h2, .info-card h3 {
  margin-bottom: 15px;
  font-weight: 600;
}

.action-btn {
  width: 100%;
  font-weight: 600;
}
</style> 